package com.tf_cut.backend.seller.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import com.tf_cut.backend.common.pojo.PageInfo;
import com.tf_cut.backend.common.pojo.Result;
import com.tf_cut.backend.seller.service.SellerAccountDetailService;
import com.tf_cut.backend.seller.service.SellerAccountService;
import com.tf_cut.backend.seller.service.SellerAndAccountService;
import com.tf_cut.backend.seller.service.SellerService;
import com.tf_cut.backend.seller.vo.SellerAccountDetailVo;
import com.tf_cut.backend.seller.vo.SellerAndAccountVo;
import com.tf_cut.backend.seller.vo.SellerAndServiceVo;
import com.tf_cut.backend.util.ConfigSettingUtil;
import com.tf_cut.backend.util.SerialNoUtil;
import com.tf_cut.backend.util.UUIDUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;


@RestController
@RequestMapping("/backend/seller/")
@Slf4j
public class SellerController {
	
	@Autowired
	private SellerService sellerService;
	
	@Autowired
	private SellerAndAccountService sellerAndAccountService;

	@Autowired
	private SellerAccountDetailService sellerAccountDetailService;
	
    @Autowired
    private SellerAccountService sellerAccountService;

	@Resource
	private ConfigSettingUtil config;
	

    @Resource
    private SerialNoUtil util;
	
	// 添加商户
	@RequestMapping("insert")
    public String insertSellerAndAccount(String json) {
		Result<SellerAndAccountVo> result = null;
		SellerAndAccountVo avo = JSON.parseObject(json, SellerAndAccountVo.class);
		try {
			if(avo.getSellerId() == null || avo.getSellerId().equals("")){
				avo.setAppSecret(UUIDUtil.getUUID());
				avo.setAppKey(UUIDUtil.getUUID().substring(0, 20));				
			}
			result = sellerService.insertSellerAndAccount(avo);
		} catch(Exception e) {
			log.error(e.getMessage(),e);
			result = Result.of(avo);
			result.setMsg(e.getMessage());
			result.setFlag(false);
		}
        return JSON.toJSONString(result);
    }

    @RequestMapping("getServiceType")
    public String getServiceType(){
		List<String> serviceTypes = config.getConfigValuesList("invoice_service_type");

		return JSON.toJSONString(serviceTypes);
	}
	
	// 更新商户基本信息
	@RequestMapping("updateInfo")
    public String updateInfo( String json) {

		SellerAndAccountVo svo = JSON.parseObject(json, SellerAndAccountVo.class);
		
		if(svo.getAppKey() == null  ||  svo.getAppKey().equals("")){
			svo.setAppKey(UUIDUtil.getUUID().substring(0, 20));
		}
		if(svo.getAppSecret() == null || svo.getAppSecret().equals("")){
			svo.setAppSecret(UUIDUtil.getUUID());
			
		}
		Result<SellerAndAccountVo> result = sellerService.save(svo);
        return JSON.toJSONString(result.getData());
    }
	
	// 更新商户基本信息
	@RequestMapping("updateStatus")
    public String updateStatus( String json) {

		SellerAndAccountVo svo = JSON.parseObject(json, SellerAndAccountVo.class);
		
		Result<SellerAndAccountVo> result = sellerService.save(svo);
        return JSON.toJSONString(result.getData());
    }
	
	// 获取代理商
	@RequestMapping("get")
    public String get( String id) {
		Result<SellerAndAccountVo> result = sellerService.get(id);
		return JSON.toJSONString(result.getData(),SerializerFeature.WriteDateUseDateFormat);
    }
	
	// 冻结（Y）/删除（D）/解冻（N） 代理商
	@RequestMapping("operation")
    public String operation(String id, String state) {
		Result<Boolean> result = Result.of(true);
		result.setFlag(true);
		try {
			SellerAndAccountVo avo = sellerService.get(id).getData();
			avo.setSellerState(state);
			sellerService.save(avo);
		} catch(Exception e) {
			log.error(e.getMessage(),e);
			result = Result.of(false);
			result.setFlag(false);
		}
		return JSON.toJSONString(result);
    }
	
	// 查找商户
	@RequestMapping("findListSeller")
	public String findListSeller(String json) {
		SellerAndAccountVo avo = JSON.parseObject(json, SellerAndAccountVo.class);
		return JSON.toJSONString(sellerAndAccountService.findListSeller(avo),SerializerFeature.WriteDateUseDateFormat);
	}
	
	// 查找商户
	@RequestMapping("findListSellerNoPage")
	public String findListSellerNoPage(String json) {
		SellerAndServiceVo avo = JSON.parseObject(json, SellerAndServiceVo.class);
		avo.setSellerState("Y");
		return JSON.toJSONString(sellerService.findSellerService(avo));
	}
	
	@PostMapping("importSeller")
	public String importSeller(String json) {
        return JSON.toJSONString(sellerService.insertSellers(json));
	}

	@RequestMapping("info/list")
	public String querySellerInfoList(String json) {
		log.info("backend seller info list reqParam={}",json);
		SellerAndAccountVo sellerAndAccountVo = JSON.parseObject(json, SellerAndAccountVo.class);
		Result<List<SellerAndAccountVo>> result;
		try {
			PageInfo<SellerAndAccountVo> sellerBillAndConsigneeVoPageInfo = sellerService.querySellerBillList(sellerAndAccountVo);
			return JSON.toJSONString(sellerBillAndConsigneeVoPageInfo, SerializerFeature.WriteDateUseDateFormat);
		} catch (Exception e) {
			log.error("querySellerInfoList error:{}", e.getMessage(), e);
			result = Result.of(Lists.newArrayList());
			result.setMsg(e.getMessage());
			result.setFlag(false);
		}
		return JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat);
	}

	@RequestMapping("qryBalance")
	public String qryBalance(String json){
		log.info("backend seller info list reqParam={}",json);
		SellerAndAccountVo sellerAndAccountVo = JSON.parseObject(json, SellerAndAccountVo.class);
		Result<List<SellerAndAccountVo>> result;
		try {
			PageInfo<SellerAndAccountVo> sellerBillAndConsigneeVoPageInfo = sellerService.querySellerBalance(sellerAndAccountVo);
			return JSON.toJSONString(sellerBillAndConsigneeVoPageInfo, SerializerFeature.WriteDateUseDateFormat);
		} catch (Exception e) {
			log.error("querySellerInfoList error:{}", e.getMessage(), e);
			result = Result.of(Lists.newArrayList());
			result.setMsg(e.getMessage());
			result.setFlag(false);
		}
		return JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat);
	}

	@RequestMapping("qryBalanceDetail")
	public String qryBalanceDetail(String json){
		SellerAccountDetailVo sellerAccountDetailVo = JSON.parseObject(json,SellerAccountDetailVo.class);
		Result<PageInfo<SellerAccountDetailVo>> result = sellerAccountDetailService.page(sellerAccountDetailVo);
		return JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat);
	}

	@RequestMapping("qryByCondition")
	public String qryByCondition(String json){
		log.info("backend seller info list reqParam={}",json);
		SellerAndAccountVo sellerAndAccountVo = JSON.parseObject(json, SellerAndAccountVo.class);
		List<SellerAndAccountVo> res = sellerAndAccountService.findByCondition(sellerAndAccountVo);
		return JSON.toJSONString(res,SerializerFeature.WriteDateUseDateFormat);
	}
	
	
	@RequestMapping("queryDetail")
	public String queryDetail(@RequestParam("page") int page,@RequestParam("rows") int rows,@RequestParam("projectCode") String projectCode){
		PageInfo<SellerAccountDetailVo> setHistoryVoPageInfo = sellerAccountDetailService.queryDetail(page,rows,projectCode);
    	return JSON.toJSONString(setHistoryVoPageInfo, SerializerFeature.WriteDateUseDateFormat);
	}
	
	@PostMapping("/update")
	public String update(@RequestParam("status") String status,@RequestParam("projectCode") String projectCode){
		return sellerAccountDetailService.updateStatu(status,projectCode);
		
	}
	
    @PostMapping("/saveSellerInfo")
    public Result<String> saveSellerInfo(@RequestBody SellerAccountDetailVo avo) {
    	Result<String> result = Result.of("商户调额成功");
    	result.setFlag(true);
    	 SellerAndAccountVo sellerAndAccountVo = SellerAndAccountVo.builder().sellerId(avo.getSellerId()).build();
    	SellerAndAccountVo retSellerAndAccountVo = sellerAccountService.findSellerAccountByCondition(sellerAndAccountVo);
    	String serviceId = sellerAccountService.findByServiceId(sellerAndAccountVo.getSellerId());
    	if(serviceId == null || serviceId.equals("")){
    		result.setData("商户未关联服务商，无法调额");
    		result.setFlag(false);
    	}else{
    		generateSellerChargeDetail(avo,avo.getTradeMoney(),"06",avo.getPaySubject(),retSellerAndAccountVo,avo.getMerchantNumber(),avo.getPlatform(), serviceId);    		
    	}
         return result;
    }
    
    /**
     * 生成明细
     * cpm_base_subject，科目表
     * @param retRecharge
     */
    private void generateSellerChargeDetail(SellerAccountDetailVo retRecharge,BigDecimal amount,String orderSource,String paySubject,SellerAndAccountVo retSellerAndAccountVo,String merchantNumber,String platform,String serviceId) {
//        Result<SellerOrderVo> retSellerOrder = generateSellerOrderVoResult(retRecharge,amount);
        generateSellerAccountDetail(retRecharge,null,orderSource,paySubject,amount,retSellerAndAccountVo.getSellerAccountId(),merchantNumber,platform,serviceId);
    }
    
    
    private void generateSellerAccountDetail(SellerAccountDetailVo retRecharge,String orderId,String orderSource,String paySubject,BigDecimal amount,String sellerAccountId,String merchantNumber,String platform,String serviceId) {
    	String serialNo = util.genSerialNo("Q","A",merchantNumber);
    	String tradeSerial = util.genSerialNo("K","A",merchantNumber);
        Timestamp now = Timestamp.valueOf(LocalDateTime.now());
        SellerAccountDetailVo sellerAccountDetailVo = new SellerAccountDetailVo();
        sellerAccountDetailVo.setTradeId(serialNo);
        sellerAccountDetailVo.setServiceId(serviceId);
        sellerAccountDetailVo.setSellerId(retRecharge.getSellerId());
        sellerAccountDetailVo.setSellerAccountId(sellerAccountId);
        sellerAccountDetailVo.setTradeSerial(tradeSerial);
        if(paySubject.equals("8")){//paySubject对应0008加款，0009扣款
        	sellerAccountDetailVo.setOrderSource(orderSource);
        }else{
        	sellerAccountDetailVo.setOrderSource("07"); 
        }
        sellerAccountDetailVo.setOperType(retRecharge.getOperType());
        sellerAccountDetailVo.setPayTime(now);
        sellerAccountDetailVo.setPaySubject("000"+paySubject);
        sellerAccountDetailVo.setPayType(1);
        sellerAccountDetailVo.setTradeMoney(amount);
        sellerAccountDetailVo.setTradeComment(retRecharge.getTradeComment());
        sellerAccountDetailVo.setIsTotal("N");
        sellerAccountDetailVo.setTotalTime(now);
        sellerAccountDetailService.save(sellerAccountDetailVo);
    }
    
    /**
     * 查询网商入驻结果
     */
    @PostMapping("registerQuery")
    public void registerQuery(String sellerId){
    	sellerService.registerQuery(sellerId);
    }
    
    /**
     * 商户入驻
     */
    @PostMapping("insertRegister")
    public String insertRegister(String sellerId){
		return JSON.toJSONString(sellerService.register(sellerId));
    }
    
    /**
     * 商户信息修改
     */
    @PostMapping("updateRegister")
    public String updateRegister(String sellerId){
		return JSON.toJSONString(sellerService.updateRegister(sellerId));
    }
    
    
    /**
     * 商户信息查询
     */
    @PostMapping("queryRegisterInfo")
    public Result<String> queryRegisterInfo(String sellerId){
    	Result<String> result = Result.of(sellerService.queryRegisterInfo(sellerId));
    	result.setFlag(true);
		return result;
    }
    
    /**
     * 专户开立
     */
    @PostMapping("regisOpen")
    public String regisOpen(String sellerId){
		return sellerService.regisOpen(sellerId);
    }
    
    
    @Scheduled(cron="0 0 0 * * ?")
    public void sellerMoney(){
    	sellerService.sellerMoney();
    }
    /**
     * 查询网商余额
     * @return
     */
    @PostMapping("findWsMoney")
    public String findWsMoney(String sellerId){
    	
		return sellerService.findWsMoney(sellerId);
    }
    
    
}
